﻿using DtRlDeviceApiNet20;
using DtRlDeviceApiNet20.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Xml.Serialization;

namespace App.Sdx.Api
{
    /// <summary>
    /// UploadPlans 的摘要说明
    /// </summary>
    public class UploadPlans : IHttpHandler
    {
        private ApiWebClientInterface _apiClientInterface = new ApiWebClientInterface();
        static string Url = ConfigurationManager.AppSettings["WriteTrainSamplingData"].ToString();
        static string SimplingCode = ConfigurationManager.AppSettings["SimplingCode"].ToString();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                if (context.Request.QueryString["paraStr"] != null)
                {
                    var josnString = context.Request.QueryString["paraStr"].ToString();
                   
                    if (!string.IsNullOrEmpty(josnString))
                    {
                        var array = josnString.Split('$');
                        TrainSamplingData trainSamplingData = new TrainSamplingData();
                        trainSamplingData.SimplingMode = "1";
                        trainSamplingData.SimplingMethod = "2";
                        trainSamplingData.CarNo = array[0];
                        trainSamplingData.SimplingPoint = Common.ToIntEx(array[1]);
                        trainSamplingData.SimplingTarget = array[2];
                        trainSamplingData.SamplingPerson = array[3];
                        trainSamplingData.SetBucketWeight = Common.ToDoubleEx(array[4]);
                        trainSamplingData.SetBucketNo = array[5];
                        trainSamplingData.SimplingLocation = array[6];
                        trainSamplingData.SimplingStartTime = Common.ToDateTimeEx(array[7]);
                        trainSamplingData.SimplingEndTime = Common.ToDateTimeEx(array[8]);
                        trainSamplingData.SupplierCode = array[9];
                        trainSamplingData.BacthInfoId = array[10];
                        trainSamplingData.SimplingCode = array[11];
                        trainSamplingData.TravelNo = array[12];
                        trainSamplingData.EmptyBucketWeight = 0;
                        var samplingId = array[15];
                        if (!string.IsNullOrEmpty(array[14]))
                        {
                            var imgData = Common.ImageToBytes(array[14]);
                            trainSamplingData.SePicMod = imgData;// array[14];
                        }

                        //LogHelper.DoErrorWrite("开始上传-------------------------------------------------");
                        //LogHelper.DoErrorWrite(josnString);
                        ReturnMsg returnMsg = this._apiClientInterface.WriteTrainSamplingData(Url, trainSamplingData);
                        //LogHelper.DoErrorWrite("ErrorCode 1:  " + this._apiClientInterface.ErrorCode);
                        //LogHelper.DoErrorWrite("ErrorText 1:  " + this._apiClientInterface.ErrorText);
                        //LogHelper.DoErrorWrite("returnMsg.Result 1:  " + returnMsg.Result);
                        if (_apiClientInterface.ErrorCode != 0)
                        {
                            LogHelper.DoErrorWrite("ErrorText 1:  " + this._apiClientInterface.ErrorText);
                            context.Response.Write(_apiClientInterface.ErrorCode);
                        }
                        else
                        {
                            if (returnMsg.Result.Contains("再次上传"))
                            {
                                //LogHelper.DoErrorWrite($"{samplingId}OK");
                                context.Response.Write($"{samplingId}OK");
                            }
                            if (returnMsg.Result == "OK")
                            {
                                //LogHelper.DoErrorWrite($"{samplingId}OK");
                                context.Response.Write($"{samplingId}OK");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.DoErrorWrite("Error:  " + ex.StackTrace);
                LogHelper.DoErrorWrite("Error:  " + ex.Message);
                context.Response.Write("Error");
            }
            finally
            {
                //LogHelper.DoErrorWrite("结束-------------------------------------------------");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public static class Common
    {

        /// <summary>
        /// 图片转字节
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static byte[] ImageToBytes(string imgPath)
        {
            try
            {
                FileStream fileStream = new FileStream(imgPath, FileMode.Open);
                byte[] array = new byte[fileStream.Length];
                fileStream.Read(array, 0, array.Length);
                fileStream.Close();
                return array;
            }
            catch
            {
                return null;
            }
        }

        public static int ToIntEx(object obj)
        {
            try
            {
                return obj == null ? 0 : Convert.ToInt32(obj);
            }
            catch
            {
                return 0;
            }
        }

        public static DateTime ToDateTimeEx(object obj)
        {
            try
            {
                return obj == null ? DateTime.Parse("1900-01-01 00:00:01") : Convert.ToDateTime(obj);
            }
            catch
            {
                return DateTime.Parse("1900-01-01 00:00:01");
            }
        }
        public static double ToDoubleEx(object obj)
        {
            try
            {
                return obj == null ? 0 : Convert.ToDouble(obj);
            }
            catch
            {
                return 0;
            }
        }
    }
}